<?php
namespace Controllers;
use Models\Task;

class CenterController extends CommonController {
    public function __construct() {
        if (!isset($_SESSION['username'])) {
            echo '<script>window.location.href="/index.php?c=user&a=login"</script>';
        }
    }
    public function index() {
        $taskModel = new Task();
        $items = $taskModel->getAll();
        $data = [
            'items' => $items
        ];
        return $this->render('center/index', $data);
    }
    public function add() {
        return $this->render('center/add');
    }
    public function doAdd() {
        $content = isset($_POST['content']) ? $_POST['content'] : '';
        if (empty($content)) return $this->jsonResponse(0, '请输入备忘内容');
        $complete_date = isset($_POST['complete_date']) ? $_POST['complete_date'] : '';
        if (empty($complete_date)) return $this->jsonResponse(0, '请输入完成日期');

        $taskModel = new Task();
        $data = [
            'content' => $content,
            'complete_date' => $complete_date
        ];
        if (!$taskModel->create($data)) {
            return $this->jsonResponse(0, '添加失败');
        }
        return $this->jsonResponse(1, '添加成功');
    }

    public function deleteTask() {
        $id = isset($_POST['task_id']) ? $_POST['task_id'] : 0;
        if (empty($id)) return $this->jsonResponse(0, '参数错误');
        $taskModel = new Task();
        if(!$taskModel->deleteById($id)) {
            return $this->jsonResponse(0, '删除失败');
        }
        return $this->jsonResponse(1, '删除成功');
    }
    public function edit() {
        $id = $_GET['id'];
        $taskModel = new Task();
        $task = $taskModel->getTaskById($id);
        $data = [
            'task' => $task
        ];
        return $this->render('center/edit', $data);
    }

    public function doEdit() {
        // update tasks set ... where id =
        $content = isset($_POST['content']) ? $_POST['content'] : '';
        if (empty($content)) return $this->jsonResponse(0, '请输入备忘内容');
        $complete_date = isset($_POST['complete_date']) ? $_POST['complete_date'] : '';
        if (empty($complete_date)) return $this->jsonResponse(0, '请输入完成日期');

        $id = $_POST['id'];
        $data = [
            'content' => $content,
            'complete_date' => $complete_date
        ];
        $taskModel = new Task();
        if($taskModel->updateById($data, $id) === false) {
            return  $this->jsonResponse(0, '保存失败');
        }
        return $this->jsonResponse(1, '保存成功');
    }
}